package com.framework.disconf.config;

import com.alibaba.dubbo.config.*;
import com.framework.disconf.property.ApplicationProperty;
import com.framework.disconf.service.ISlaveUserService;
import com.qitoon.framework.organ.service.IOrganizationService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DubboConfig {

    @Bean
    public ApplicationConfig applicationConfig() {
        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName("disconf-demo");
        return applicationConfig;
    }

    @Bean
    public RegistryConfig registryConfig(ApplicationProperty applicationProperty) {
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setProtocol("zookeeper");
        registryConfig.setAddress(applicationProperty.getZkHost());
        return registryConfig;
    }

    @Bean
    public ProtocolConfig protocolConfig() {
        ProtocolConfig protocol = new ProtocolConfig();
        protocol.setName("dubbo");
        protocol.setPort(20996);
        protocol.setThreads(200);
        return protocol;
    }

    @Bean
    public IOrganizationService getOrganizationService(ApplicationConfig config, RegistryConfig registryConfig){
        ReferenceConfig<IOrganizationService> reference = new ReferenceConfig<>();
        reference.setApplication(config);
        reference.setRegistry(registryConfig);
        reference.setInterface(IOrganizationService.class);
        return reference.get();
    }

    @Bean
    public ServiceConfig<ISlaveUserService> registryISlaveUserService(ApplicationConfig application, RegistryConfig registryConfig, ProtocolConfig protocol, ISlaveUserService slaveUserService){
        // 服务提供者暴露服务配置
        ServiceConfig<ISlaveUserService> service = new ServiceConfig<>(); // 此实例很重，封装了与注册中心的连接，请自行缓存，否则可能造成内存和连接泄漏
        service.setApplication(application);
        service.setRegistry(registryConfig); // 多个注册中心可以用setRegistries()
        service.setProtocol(protocol); // 多个协议可以用setProtocols()
        service.setInterface(ISlaveUserService.class);
        service.setRef(slaveUserService);

        // 暴露及注册服务
        service.export();
        return service;
    }
}
